<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 问答与图像识别</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
        }

        #container {
            display: flex;
            width: 100%;
            height: 100%;
        }

        #ai-responses,
        #user-input {
            width: 50%;
            padding: 20px;
            box-sizing: border-box;
            overflow-y: auto;
            border-right: 1px solid #ccc;
        }

        #user-input {
            border-right: none;
        }

        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
        }

        .ai-message {
            background-color: #f1f1f1;
        }

        .user-message {
            background-color: #d1e7ff;
            text-align: right;
        }

        #input-box {
            margin-top: 20px;
        }

        #input-box input {
            width: 80%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }

        #input-box button {
            padding: 10px;
            border: 1px solid #007bff;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }

        #input-box button:hover {
            background-color: #0056b3;
        }

        #image-upload {
            margin-top: 20px;
        }

        #image-upload input {
            display: none;
        }

        #image-upload label {
            padding: 10px;
            border: 1px solid #007bff;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }

        #image-preview {
            margin-top: 15px;
            max-width: 100%;
            max-height: 300px;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
</head>

<body>
    <div id="container">
        <div id="ai-responses">
            <h2>AI 回答</h2>
            <div id="ai-messages"></div>
        </div>
        <div id="user-input">
            <h2>用户输入</h2>
            <div id="user-messages"></div>
            <div id="input-box">
                <input type="text" id="user-input-field" placeholder="输入问题...">
                <button onclick="sendMessage()">发送</button>
            </div>
            <div id="image-upload">
                <label for="image-input">上传或粘贴图片</label>
                <input type="file" id="image-input" accept="image/*">
                <img id="image-preview" src="" alt="图片预览">
            </div>
        </div>
    </div>

    <script>
        function sendMessage() {
            const inputField = document.getElementById('user-input-field');
            const userMessage = inputField.value.trim();
            if (!userMessage) return;

            // 显示用户消息
            displayUserMessage(userMessage);

            // 清空输入框
            inputField.value = '';

            // 使用 fetch 发送 POST 请求
            fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message: userMessage })
            })
                .then(response => response.json())
                .then(data => {
                    displayAiMessage(data.result || '未获取到回复');
                })
                .catch(error => {
                    console.error('请求失败:', error);
                    displayAiMessage('请求失败');
                });
        }

        function displayUserMessage(message) {
            const userMessagesDiv = document.getElementById('user-messages');
            const newUserMessage = createMessageContainer('user-message');
            newUserMessage.textContent = message;
            userMessagesDiv.appendChild(newUserMessage);
        }

        function displayAiMessage(message) {
            const aiMessagesDiv = document.getElementById('ai-messages');
            const newAiMessage = createMessageContainer('ai-message');

            // 使用 marked 解析并用 DOMPurify 清理
            const sanitizedHTML = DOMPurify.sanitize(marked.parse(message));
            newAiMessage.innerHTML = sanitizedHTML;
            aiMessagesDiv.appendChild(newAiMessage);
        }

        function createMessageContainer(className) {
            const newMessage = document.createElement('div');
            newMessage.className = `message ${className}`;
            return newMessage;
        }

        document.getElementById('image-input').addEventListener('change', function (event) {
            handleImageUpload(event.target.files[0]);
        });

        document.addEventListener('paste', function (event) {
            const items = (event.clipboardData || event.originalEvent.clipboardData).items;
            for (const item of items) {
                if (item.type.indexOf('image') === 0) {
                    handleImageUpload(item.getAsFile());
                }
            }
        });

        function handleImageUpload(file) {
            if (!file) return;
            const reader = new FileReader();
            reader.onload = function (e) {
                const img = document.getElementById('image-preview');
                img.src = e.target.result;

                displayAiMessage('正在处理图片，请稍候...');

                const formData = new FormData();
                formData.append('image', file);
                fetch('/upload-image', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        displayAiMessage(data.result || '无法识别图像内容');
                    })
                    .catch(error => {
                        console.error('图像上传错误:', error);
                        displayAiMessage('请求失败');
                    });
            };
            reader.readAsDataURL(file);
        }
    </script>
</body>

</html>